package models

import (
	db "hais.pw/admin/database"
	utils "hais.pw/admin/utils"
)

type User struct {
	ID       int    `json:"id" form:"id"`
	Username string `json:"username" form:"username"`
	Password string `json:"password" form:"password"`
}

func (u *User) Add() (user User, err error) {
	rs, err := db.Sql.Exec("INSERT INTO User(username,password)VALUES(?,?)", u.Username, u.Password)
	utils.PrintError(err)
	user = *u
	id, err := rs.LastInsertId()
	user.ID = int(id)
	return
}

func (u *User) Delete() (rows int, err error) {
	rs, err := db.Sql.Exec("DELETE FROM User WHERE id=?", u.ID)
	utils.PrintError(err)
	row, err := rs.RowsAffected()
	rows = int(row)
	return
}

func (u *User) Get() (user User, err error) {
	err = db.Sql.QueryRow("SELECT id,username,password FROM User WHERE id=?", u.ID).Scan(&user.ID, &user.Username, &user.Password)
	utils.PrintError(err)
	return
}

func (u *User) All() (users []User, err error) {
	users = make([]User, 0)
	rows,err := db.Sql.Query("SELECT id,username,password FROM User")
	defer rows.Close()

	for rows.Next(){
		var user User
		rows.Scan(&user.ID,&user.Username,&user.Password)
		users = append(users,user)
	}

	utils.PrintError(err)
	return
}

func (u *User)Update()(rows int,err error)  {
	rs, err := db.Sql.Exec("UPDATE User SET username=?,password=? WHERE id=?", u.Username,u.Password,u.ID)
	utils.PrintError(err)
	row, err := rs.RowsAffected()
	rows = int(row)
	return
}
